package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection {

	public static void testDriver() throws Exception {
		System.out.println("Initializing Server... ");
		try {
			Class.forName("org.gjt.mm.mysql.Driver");
			System.out.println(" Driver Found.");
		} catch (ClassNotFoundException e) {
			System.out.println(" Driver Not Found, exiting..");
			throw (e);
		}
	}

	public static synchronized Connection getConnection(String host,
			String userDB, String passDB, String database) throws SQLException {
		String url = "";
		try {
			url = "jdbc:mysql://localhost/" + database;

			Connection con = DriverManager.getConnection(url, userDB, passDB);
			System.out.println(" Database connection established to " + url
					+ ".");

			return con;
		} catch (java.sql.SQLException e) {
			System.out.println(" Connection couldn't be established to " + url);
			throw (e);
		}
	}

	public static synchronized Connection getDefaultConnection()
			throws SQLException {
		return getConnection("127.0.0.1", "root", "", "voting_system");
	}

	public static synchronized void closeConnection(Connection con) {
		try {
			con.close();
			System.out.println("Connection closed");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws Exception {
		DBConnection.testDriver();
		Connection con = DBConnection.getConnection("127.0.0.1", "root", "",
				"voting_system");

		DBConnection.closeConnection(con);
	}
}
